package com.xiyue.leaspring.action;

import com.xiyue.leaspring.service.IGoodsService;
import com.xiyue.leaspring.util.web.SplitPageUtil;
import com.xiyue.leaspring.vo.Goods;
import com.xiyue.leaspring.vo.Item;
import com.xiyue.leaspring.vo.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

@Controller//定义控制器
@RequestMapping("/pages/back/admin")//父路径
public class GoodsAction extends AbstractAction{//自定义Action程序类

    private Logger logger = LoggerFactory.getLogger(GoodsAction.class);//日志记录

    @Autowired
    private IGoodsService goodsService;

    @RequestMapping("/good_add")
    public ModelAndView addView(){
        Map<String,Object> map = this.goodsService.preAdd();
        this.logger.info("商品信息增加前信息查询："+map);
        ModelAndView mav = new ModelAndView("/back/admin/goods/goods_add");
        mav.addAllObjects(map);//保存商品分类与标签数据
        return mav;
    }

    @PostMapping("/add")
    public ModelAndView add(Goods goods, long iid, String tid[],
                            MultipartFile pic)throws Exception{
        ModelAndView mav = new ModelAndView("redirect:/pages/back/admin/list");//获取路径
        String msg = "商品数据增加失败！";
        String url = "pages/back/admin/good_add";//显示后的跳转路径
        List<Tag> allTags = new ArrayList<>();
        for (int x=0;x<tid.length;x++){//将标签信息保存到集合中
            Tag tag = new Tag();
            tag.setTid(Long.parseLong(tid[x]));//保存tid编号
            allTags.add(tag);
        }
        Item item = new Item();
        item.setIid(iid);//保存iid编号
        goods.setItem(item);//保存商品与分类关系
        goods.setTags(allTags);//保存商品与标签关系
        if(pic == null && pic.isEmpty()){
            goods.setPhoto("nophoto.png");//默认图片名称
        }else {//创建新的图片名称
            goods.setPhoto(UUID.randomUUID()+"."+pic.getContentType()
             .substring(pic.getContentType().lastIndexOf("/")+1));
        }
        if(this.goodsService.add(goods)){//保存成功
            if(!(pic == null && pic.isEmpty())){//有文件上传
                String photoPath = ContextLoader.getCurrentWebApplicationContext()
                        .getServletContext().getRealPath("/upload/")+goods.getPhoto();
                File file = new File(photoPath);
                File filePath = new File(file.getParent());
                if(!filePath.exists() && !filePath.isDirectory()){
                    filePath.mkdirs();
                }
                if(!file.exists()){
                    file.createNewFile();
                }
                pic.transferTo(file);//保存上传文件
            }
            msg = "商品数据增加成功！";
        }
        mav.addObject("msg",msg);//保存提示信息
        mav.addObject("url",url);//保存跳转路径
        return mav;
    }

    @RequestMapping("/list")
    public ModelAndView list(){
        ModelAndView mav = new ModelAndView("/back/admin/goods/goods_list");
        SplitPageUtil spu = new SplitPageUtil("/pages/back/admin/goods/list");
        mav.addAllObjects(this.goodsService.list(spu.getKeyWord()
                ,spu.getCurrentPage(),spu.getLineSize()));
        return mav;
    }

    @GetMapping("/editview")
    public ModelAndView editView(Long gid){
        Map<String,Object> map = this.goodsService.preEdit(gid);//查询商品信息
        this.logger.info("商品信息修改前信息查询："+map);
        ModelAndView mav = new ModelAndView("/back/admin/goods/goods_edit");
        mav.addAllObjects(map);
        return mav;
    }

    @PostMapping("/editsave")
    public ModelAndView edit(Goods goods, long iid, String tid[],
                             MultipartFile pic)throws Exception{
            ModelAndView mav = new ModelAndView("redirect:/pages/back/admin/list");//获取路径
            String msg = "商品数据修改失败！";
            String url = "pages/back/admin/list";//显示后的跳转路径
            List<Tag> allTags = new ArrayList<>();
            for (int x=0;x<tid.length;x++){//将标签信息保存到集合中
                Tag tag = new Tag();
                tag.setTid(Long.parseLong(tid[x]));//保存tid编号
                allTags.add(tag);
            }
            Item item = new Item();
            item.setIid(iid);//保存iid编号
            goods.setItem(item);//保存商品与分类关系
            goods.setTags(allTags);//保存商品与标签关系
            if(!pic.isEmpty()){//有新的文件上传
                goods.setPhoto("nophoto.png");//默认图片名称
                if("nophoto.png".equals(goods.getPhoto())){
                    goods.setPhoto(UUID.randomUUID()+"."+pic.getContentType()
                            .substring(pic.getContentType().lastIndexOf("/")+1));
                }
            }
            if(this.goodsService.add(goods)){//保存成功
                if(!(pic == null && pic.isEmpty())){//有文件上传
                    String photoPath = ContextLoader.getCurrentWebApplicationContext()
                            .getServletContext().getRealPath("/upload/")+goods.getPhoto();
                    File file = new File(photoPath);
                    File filePath = new File(file.getParent());
                    if(!filePath.exists() && !filePath.isDirectory()){
                        filePath.mkdirs();
                    }
                    if(!file.exists()){
                        file.createNewFile();
                    }
                    pic.transferTo(file);//保存上传文件
                }
                msg = "商品数据修改成功！";
            }
            mav.addObject("msg",msg);//保存提示信息
            mav.addObject("url",url);//保存跳转路径
            return mav;
    }

    @RequestMapping("/delete")
    public ModelAndView delete(String ids){
        String msg = "商品数据删除失败！";
        String url = "pages/back/admin/list";//显示后的跳转路径
        ModelAndView mav = new ModelAndView("redirect:/pages/back/admin/list");//获取路径
        //传递要删除的所有商品ID，多个ID间用“,”分隔
        String idData[] = ids.split(",");
        Set<Long> gids = new HashSet<>();
        for (String id:idData) {
            gids.add(Long.parseLong(id));
        }
        if(this.goodsService.remove(gids)){
            msg = "商品数据删除成功！";
        }
        mav.addObject("msg",msg);
        mav.addObject("url",url);
        return mav;
    }

}
